package com.mida.bms.report.process.impl;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.mida.bms.report.common.cons.CharacterConst;
import com.mida.bms.report.entity.DocStructReport;
import com.mida.bms.report.process.DocReportPdfProcess;
import com.mida.bms.report.service.DocReportPdfService;
import com.mida.bms.report.service.DocReportService;
import com.mida.bms.report.vo.ReportSearchRequest;
import com.mida.tool.common.result.ListResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 报告PDF相关处理
 */
@Service
@Slf4j
public class DocReportPdfProcessImpl implements DocReportPdfProcess {

    /**
     * docReportService
     */
    @Autowired
    private DocReportService docReportService;


    /**
     * docReportPdfService
     */
    @Autowired
    private DocReportPdfService docReportPdfService;

    /**
     * 根据报告soid、以及状态和就诊场景，追加相关水印 获取文件流
     *
     * @param request
     * @param httpServletResponse
     */
    @Override
    public void gainReportPdf(ReportSearchRequest request,
                              HttpServletResponse httpServletResponse) {

        log.info("开始获取报告pdf");
        StopWatch stopWatch = StopWatch.createStarted();
        ListResult listResult = new ListResult();
        String pdfPath = request.getPdfPath();
        GetMethod getMethod = null;
        OutputStream outputStream = null;
        String strWaterMark = request.getWaterMark();
        try {

            outputStream = httpServletResponse.getOutputStream();

            if (StringUtils.isNotEmpty(strWaterMark)) {
                setWaterMark(strWaterMark, outputStream, pdfPath);
            }

            httpServletResponse.setContentType("application/pdf;charset=UTF-8");
            httpServletResponse.addHeader("Content-Disposition", "inline;filename=");
            HttpClient httpClient = new HttpClient();
            getMethod = new GetMethod(pdfPath);
            httpClient.executeMethod(getMethod);
            byte[] response = getMethod.getResponseBody();
            outputStream.write(response);

        } catch (Exception e) {
            log.error("本次获取报告pdf发送异常", e);
        } finally {
            if (getMethod != null) {
                getMethod.releaseConnection();
            }
            try {
                stopWatch.stop();
                log.info("本次获取报告pdf耗时: " + stopWatch.getTime() + "ms");
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("pdf文件流关闭失败");
            }
        }
    }

    /**
     * @param request
     * @return
     */
    @Override
    public DocStructReport gainDocReportByStReportSoid(ReportSearchRequest request)
            throws Exception {
        return docReportService.gainDocReportByStReportSoid(request.getStReportSoid());
    }

    /**
     * 根据报告soid, 返回url
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public String gainReportPdfByStReportSoid(ReportSearchRequest request) throws Exception {
        return docReportPdfService.gainReportPdfByStReportSoid(request);
    }


    /**
     * 设置水印内容
     * @param waterMarkName
     * @param outputStream
     * @param pdfPath
     * @throws Exception
     */
    private void setWaterMark(String waterMarkName, OutputStream outputStream, String pdfPath) throws Exception {
        PdfReader reader = new PdfReader(pdfPath);
        PdfStamper stamper = new PdfStamper(reader, outputStream);
        //这里的字体设置比较关键，这个设置是支持中文的写法
        BaseFont base = BaseFont.createFont("STSong-Light",
                "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
        int total = reader.getNumberOfPages() + 1;

        PdfContentByte under;
        Rectangle pageRect = null;
        for (int i = 1; i < total; i++) {
            pageRect = stamper.getReader().
                    getPageSizeWithRotation(i);
            // 计算水印X,Y坐标
            float x = pageRect.getWidth() / 10;
            float y = pageRect.getHeight() / 10 - 10;
            // 获得PDF最顶层
            under = stamper.getOverContent(i);
            under.saveState();
            // set Transparency
            PdfGState gs = new PdfGState();
            // 设置透明度为0.2
            gs.setFillOpacity(1.f);
            under.setGState(gs);
            under.restoreState();
            under.beginText();
            under.setFontAndSize(base, 60);
            under.setColorFill(BaseColor.ORANGE);

            // 水印文字成45度角倾斜
            under.showTextAligned(Element.ALIGN_CENTER
                    , waterMarkName, x,
                    y, 55);
            // 添加水印文字
            under.endText();
            under.setLineWidth(1f);
            under.stroke();
        }
        stamper.close();
    }
}
